package cn.yzgy.yzgyoa.common.service.impl;

import cn.yzgy.yzgyoa.common.crsp.StatusCode;
import cn.yzgy.yzgyoa.common.entity.SysFileInfo;
import cn.yzgy.yzgyoa.common.properties.MessageProperties;
import cn.yzgy.yzgyoa.common.service.FileUpAndDownService;
import cn.yzgy.yzgyoa.common.utils.SnowflakeIdWorker;
import cn.yzgy.yzgyoa.ucenter.entity.UserInfoDetail;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.avalon.framework.service.ServiceException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 * 文件上传实现类
 * @author Yqsen
 * @version 0.0.1
 * @since 2021年11月3日13:42:53
 */

@Service
public class FileUpAndDownServiceImpl implements FileUpAndDownService {

    /**
     * 用来获取file-message.properties配置文件中的信息
     */
    private final MessageProperties config;
    public FileUpAndDownServiceImpl(MessageProperties config) {
        this.config = config;
    }

    public Map<String, Object> uploadFiles(MultipartFile file, String busiId) throws ServiceException {
        try {
            Map<String, Object> resMap = new HashMap<>();
            String[] filesType = config.getFileType().split(",");
            String path ;
            boolean flag = false;
            for (String type : filesType) {
                if (StringUtils.endsWithIgnoreCase(file.getOriginalFilename(), type)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                resMap.put("result", StatusCode.SUCCESS);
                // 获得文件名称
                String oldFileName = file.getOriginalFilename();

                // 年月日文件夹
                //SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                //String basedir = sdf.format(new Date());

                int kb = (int) (file.getSize()/1024);
                if(kb<1024){
                    resMap.put("fileSize",kb+"KB");
                }else{
                    resMap.put("fileSize",kb/1024+"MB");
                }
                // 进行压缩(大于4M)
                if (file.getSize() > config.getFileSize()) {
                    // 重新生成
                    String newUuid = UUID.randomUUID().toString().replaceAll("-", "");
/*
                    path = config.getUpPath() + "/" +basedir + "/" +busiId + "/" + newUuid + oldFileName;
*/
                    path = config.getUpPath() + "/" +busiId + "/" + newUuid + oldFileName;
                    // 如果目录不存在则创建目录
                    File oldFile = new File(path);
                    if (!oldFile.exists()) {
                        oldFile.mkdirs();
                    }
                    file.transferTo(oldFile);
                    // 压缩图片
                    Thumbnails.of(oldFile).scale(config.getScaleRatio()).toFile(path);
                    // 显示路径
                    resMap.put("path", config.getUpPath() + "/" +busiId + "/" + newUuid + oldFileName);
                } else {
                    path = config.getUpPath() +  "/" +busiId + "/" + oldFileName;
                    // 如果目录不存在则创建目录
                    File uploadFile = new File(path);
                    if (!uploadFile.exists()) {
                        uploadFile.mkdirs();
                    }
                    file.transferTo(uploadFile);
                    // 显示路径
                    resMap.put("path", config.getUpPath() + "/" +busiId + "/" + oldFileName);
                }

                resMap.put("fileName", file.getOriginalFilename());
            } else {
                resMap.put("result", "文件格式不正确,支持png|jpg|jpeg|word|xls|xlxs|pdf");
            }
            return resMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
    }

    @Override
    public String uploadFile(MultipartFile file, String busiId, UserInfoDetail currentUser) {
        try {
            if (!file.isEmpty()) {
                SysFileInfo sysFileInfo = new SysFileInfo();
                Map<String, Object> picMap = uploadFiles(file,busiId);
                long snowflakeId = SnowflakeIdWorker.getNext();
                //存入文件表 并返回文件id
                boolean insert = sysFileInfo.setFileId(snowflakeId)
                        .setFileName(picMap.get("fileName") + "")
                        .setBusiId(Long.parseLong(busiId))
                        .setFileSize(picMap.get("fileSize")+"")
                        .setFilePath(picMap.get("path") + "")
                        .setCreateBy(currentUser.getUid())
                        .insert();
                if(insert){
                    return sysFileInfo.getFileId().toString();
                }
            } else {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public SysFileInfo getFilePath(SysFileInfo queryDto) {
        return queryDto.selectById();
    }
}
